<?php


namespace app\common\wechat;
use app\common\wechat\WechatConfig;
use think\App;

/**
 * 微信小程序登陆类
 * Class WeChat
 * @package app\api\common
 */
class WechatMiniLogin extends WechatConfig
{
    protected $sysConfig;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 通过code获取微信用户信息
     * @param $code
     * @return array
     */
    public function getWeChatInfoByCode($code)
    {
        if (empty($code)) return ['code' => 0, 'msg' => 'code错误'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appid . "&secret=" . $this->app_secret . "&js_code=" . $code . "&grant_type=authorization_code";
        $infos = json_decode(file_get_contents($url));
        $openid = $infos->openid ?? 0;
        if (!$openid) {
            return ['code' => 202, 'msg' => '未获取到用户openid'];
        }




        return ['code' => 200, 'msg' => 'openid获取成功', 'data' => $infos];
    }

    /**
     * 解密手机号
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     * @return mixed|string
     */
    public function getPhone($code){
        $ACCESS_TOKEN = $this->getAccessToken();

        $qcode = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$ACCESS_TOKEN";
        $param = json_encode([
            "code"=> $code,
        ]);
        //POST参数
        $result = $this->httpRequest($qcode, $param, "POST");
        $res=json_decode($result,true);
        $phone='';
        if($res['errcode']==0 && $res['errmsg']=='ok'){
            $phone=$res['phone_info']['phoneNumber'];
        }
        return $phone;
    }

    

    private function getAccessToken() {

        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->app_secret";

        $access_res=file_get_contents($url);
        $access_res=json_decode($access_res,true);
        $access_token=$access_res['access_token'];
        return $access_token;
    }



}